#include <unistd.h>
#include <iostream>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <wait.h>
void handler(int num)
{
    std::cout << "子进程没了，悲" << std::endl;
    while (true)
    {
        pid_t id = waitpid(-1, nullptr, WNOHANG);
        if (id > 0)
            std::cout << "成功回收一个子进程" << std::endl;
        else if(id==0){
        std::cout<<"退出的子进程已完成回收"<<std::endl;
        break;
    }
        else{
            std::cout<<"回收发生错误"<<std::endl;
            break;
    }
}
}
int main()
{
    signal(SIGCHLD, handler);
    for (int i = 0; i < 10; i++)
    {
        pid_t id = fork();
        if (id == 0)
        {
            if(i==9)
            sleep(2);
            sleep(1);
            std::cout << "子进程退出" << std::endl;
            exit(0);
        }
    }
    while(1)
    sleep(1);
    return 0;
}